<template lang="pug">
el-drawer.commonDrawer(
    :title="'添加发展里程检表'"
    :visible.sync="visibleDialog"
    custom-class="commonDrawer"
    direction="rtl"
    size="1080px"
    append-to-body
    destroy-on-close
    modal-append-to-body
  )
    .drawer-content
      form-box(
        ref="form"
        :fields="fields"
        :showBtns="false"
        :layoutCol="{ xs: 24, md: 24, lg: 24 }"
      )
        div(slot="form-children")
          el-button( icon="el-icon-circle-plus" round plain @click="addChildren") 选择宝宝
          div(class="tag-div")
            el-tag(v-for="(tag, index) in childrenList" :key="index" class="tag-item" closable @close="deleteHandle(tag)") {{tag.name}}
        template(slot="form-develop")
          div.tab
            el-table(
              :data="tableObj.data"
              :span-method="objectSpanMethod"
            )
              el-table-column(prop="name" label="项目" width="120px")
              el-table-column(label="检核")
                template(slot-scope="scope" width="160px")
                  <!--el-checkbox(v-model="scope.row.checked")-->
                  el-radio-group(v-model="scope.row.checked" size="small")
                    el-radio-button(label="1") 已达到
                    el-radio-button(label="2") 发展中
                    el-radio-button(label="0") 未达成
              el-table-column(prop="target" label="评量指标" width="240px")
              el-table-column(prop="details" label="说明")
    .drawer-footer.tr
      el-button.gradientVertical(size="large" :loading="submitting" @click="submitHandle" round) 提交
    table-selector(
      @sureHandle="sureHandle"
      :visible.sync="childrenVisible"
      :value="value"
      :column="children.column"
      :search-config="children.searchConfig"
      label="宝宝"
      :single="false"
      reqMethod="POST"
      :queryPropsParams="{ areaId: curArea.areaId }"
      req-url="web/children/page")
</template>
<script>
import { mapGetters } from 'vuex'
import TableSelector from '@/components/Basic/TableSelector'
import AImage from '@/components/Basic/Image'
import { childrenColumn, seachConfigClient } from '../config'
import { getClassesByArea } from '@/api/common'
import { isEmpty } from '@/utils/util'
export const column = [
  {
    prop: 'name',
    label: '项目'
  },
  {
    prop: 'check',
    label: '检核'
  },
  {
    prop: 'target',
    label: '评量指标'
  },
  {
    prop: 'details',
    label: '说明'
  }
]
import { getMonthDevelopReview, getMonthDevelopReviewItem, addDevelopReview } from '../api'
export default {
  components: {
    AImage,
    TableSelector
  },
  props: {
    id: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    },
    childrenId: {
      type: String,
      default: ''
    },
    classesId: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      tableObj: {
        column,
        data: []
      },
      submitting: false,
      developId: '',
      monthList: [],

      classes: [],
      childrenList: [],
      value: [],
      childrenVisible: false
    }
  },
  computed: {
    ...mapGetters(['curArea']),
    visibleDialog: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    },
    children () {
      return {
        column: childrenColumn,
        searchConfig: seachConfigClient(this.classes)
      }
    },
    fields () {
      const { monthList } = this
      return [
        {
          label: '选择宝宝',
          key: 'children',
          type: 'slot'
        },
        {
          label: '检表类型',
          key: 'type',
          type: 'select',
          rules: [{ required: true, message: '请选择' }],
          fieldProps: {
            options: [
              {
                id: '0',
                name: '机构端'
              },
              {
                id: '1',
                name: '家庭端'
              },
              {
                id: '2',
                name: '小群体课程'
              }
            ],
            props: { value: 'id', label: 'name' }
          },
          events: {
            change: val => this.typeChange(val)
          }
        },
        {
          key: 'monthAge',
          label: '月龄',
          type: 'select',
          rules: [{ required: true, message: '请选择' }],
          fieldProps: {
            options: monthList,
            props: { value: 'id', label: 'name' }
          },
          events: {
            change: val => this.monthChange(val)
          }
        },
        {
          key: 'develop',
          label: '检表',
          type: 'slot'
        },
        {
          key: 'remarks',
          label: '简述',
          rules: [{ required: true, message: '请输入' }],
          type: 'textarea'
        }
      ]
    }
  },
  created () {
    this.getClasses()
  },
  methods: {
    objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
      const spanArr = this.getSpanArr(this.tableObj.data, 'name')
      const _row = spanArr[rowIndex]
      if (columnIndex === 0) {
        if (_row > 0) {
          return {
            rowspan: _row,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    },

    getSpanArr (data, spanKey) {
      const spanArr = []
      let pos = ''
      for (let i = 0; i < data.length; i++) {
        if (i === 0) {
          spanArr.push(1)
          pos = 0
        } else {
          if (data[i][spanKey] === data[i - 1][spanKey]) {
            spanArr[pos] += 1
            spanArr.push(0)
          } else {
            spanArr.push(1)
            pos = i
          }
        }
      }
      return spanArr
    },

    async submitHandle () {
      const { childrenList } = this
      if (childrenList.length === 0) {
        this.$message.warning('请先选择宝宝')
        return
      }

      let checked = true
      const list = this.tableObj.data.map(x => {
        if (isEmpty(x.checked)) {
          checked = false
        }
        return {
          developItemId: x.id,
          states: x.checked
        }
      })
      if (!checked) {
        this.$message.warning('请先完成检表填写')
        return
      }

      const { developId } = this
      const values = await this.$refs.form.submitForm()

      const childrenIds = childrenList.map(x => {
        return x.id
      }).join(',')
      const classIds = childrenList.map(x => {
        return x.classesId
      }).join(',')

      const params = {
        ...values,
        childrenIds,
        classIds,
        list,
        developId
      }
      addDevelopReview(params).then(res => {
        console.log(res)
        this.$emit('getList')
        this.$_handleCancel()
        this.$message.success('保存成功')
      })
    },

    typeChange (res) {
      console.log(res)
      this.getMonth(res)
    },
    monthChange (res) {
      console.log(res)
      this.developId = res
      getMonthDevelopReviewItem({ developId: res }).then(res => {
        console.log(res)
        this.tableObj.data = res
      })
    },
    $_handleCancel () {
      this.visibleDialog = false
    },

    getMonth (value) {
      getMonthDevelopReview({ type: value }).then(res => {
        this.monthList = res
      })
    },

    addChildren () {
      this.value = [...this.childrenList]
      this.childrenVisible = true
    },

    // 删除标签
    deleteHandle (tag) {
      const { childrenList } = this
      this.childrenList = [...childrenList.filter(x => x.id !== tag.id)]
    },

    sureHandle (data) {
      console.log(data)
      this.childrenList = data
    },

    async getClasses () {
      const { curArea } = this
      this.classes = await (getClassesByArea({ areaId: curArea.areaId }) || [])
    }
  }
}
</script>
<style lang="scss" scoped>
.tag-div {
  margin-top: 10px;

  .tag-item {
    margin-right: 10px;
    margin-top: 10px;
  }
}

.tab {
  ::v-deep {
    th.is-leaf {
      height: 66px;
    }

    th {
      color: #000;
      font-size: 17px;
      background: #FAFAFA;
      font-family: PingFang SC;
      font-weight: bold;
    }

    td {
      padding: 20px 0
    }

    .el-table__empty-text {
      display: none;
    }

    .el-table__empty-block {
      padding: 30px;
      padding-bottom: 50px;
    }

    .el-table__empty-block:after {
      content: "暂无数据";
      position: absolute;
      bottom: 0;
    }

    .el-table__empty-block:before {
      content: "";
      /* 必须设置 content 属性，即使它是空字符串 */
      display: block;
      /* 确保伪元素以块级元素显示 */
      width: 500px;
      /* 设置宽度 */
      height: 300px;
      /* 设置高度 */
      background-image: url('../../../../../assets/quesheng.png');
      /* 添加背景图片 */
      background-size: 100% 100%;
    }
  }
}
</style>
